package com.olmarket.core.service;

import com.github.pagehelper.PageHelper;
import com.olmarket.core.dao.UserDAO;
import com.olmarket.core.dto.GoodDetailResult;
import com.olmarket.core.dto.GoodParam;
import com.olmarket.core.dto.RequestDetailResult;
import com.olmarket.core.dto.RequestsParam;
import com.olmarket.core.entity.*;
import com.olmarket.core.exception.Asserts;
import com.olmarket.core.util.JwtUtil;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author h'zh
 * @date: 12.14
 */

//TODO:适配Controller
@Service
public class UserService {

    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserDAO userDAO;
    @Autowired
    StringEncryptor stringEncryptor;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtUtil jwtUtil;

    //根据用户名获取用户信息
    public User getUserByUsername(String username) {
        return userDAO.getUserByUsername(username);
    }

    //处理用户登录
    public String login(String username, String password, int userType) {
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                Asserts.fail("密码不正确");
            }

            if (((SecurityUserDetails) userDetails).getUserType() != userType) {
                Asserts.fail("用户身份错误");
            }

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return jwtUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOG.warn("登陆失败: " + e.getMessage());
            Asserts.fail("用户不存在");
        }
        return null;
    }


    //获取用户信息(加密)
    public UserDetails loadUserByUsername(String username) {
        User user = getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return new SecurityUserDetails(user);
    }


    //创建用户
    public int createUser(String username, String password, int userType) {
        User user = new User();
        user.setUsername(username);
        user.setUserType(userType);
        if (password == null || password.isEmpty()) {
            user.setPassword("88888888");
        } else {
            user.setPassword(password);
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        int i = userDAO.createUser(user);
//        return i > 0 ? user.getUserid() : 0;
        System.out.println("userService.createUser i = " + i);
        return i;
    }

    public int createStudent(int userId, String name, boolean sex, String address, String qq, String tel){
        UserStudent userStudent = new UserStudent();
        userStudent.setUserId(userId);
        userStudent.setName(name);
        userStudent.setSex(sex);
        userStudent.setAddress(address);
        userStudent.setQq(qq);
        userStudent.setTel(tel);
        return userDAO.createStudent(userStudent);
    }

    public List<UserStudent> findAllStudentId() {
        List<UserStudent> allUser = userDAO.getAllStudentId();
        return allUser;
    }

    //根据Id查询学生信息
    public UserStudent searchStudentById(String id) {
        return userDAO.searchStudentById(id);
    }

    //根据Id修改学生信息
    public int modifyGroup(UserStudent userStudent) {
        return userDAO.modifyStudent(userStudent);
    }

    //批量删除学生
    public int deleteGroupBatch(List<Integer> studentIds) {
        for (int studentId : studentIds) {
            int userId = userDAO.getUserIdByGroupId(studentId);
            userDAO.deleteUser(userId);
        }
        return userDAO.deleteStudentBatch(studentIds);
    }


    public int updateGroupPassword(int studentId, String newPassword) {
        return userDAO.updateUserPassword(studentId, passwordEncoder.encode(newPassword));
    }

    public int resetGroupPwdBatch(List<Integer> studentIds, String pwd) {
        return 0;
    }

    //创建新的学生
    public int addGroup(UserStudent userStudent) {
        return userDAO.createStudent(userStudent);
    }


    //根据关键词搜索学生信息
    //删除特定的类型
    public int deleteType(int typeId) {
        return userDAO.deleteType(typeId);
    }

    //创建新的类型
    public int addType(Type newType) {
        return userDAO.addType(newType);
    }

    //修改类型
    public int updateType(Type type) {
        return userDAO.updateType(type);
    }

    public List<Type> getAllTypes() {
        return userDAO.getAllTypes();
    }

    public int deleteStudentBatch(List<Integer> studentIds) {
        return 0;
    }

    public int updateStudentPassword(int id, String password) {
        return 0;
    }

    //修改学生的信息
    public int modifyStudent(UserStudent userStudent) {
        return userDAO.modifyStudent(userStudent);
    }

    public int resetStudentPwdBatch(List<Integer> ids, String password) {
        return 0;
    }

    public List<UserStudent> searchStudent(int pageNum, int pageSize, String keyword, int id) {
        if (pageSize == -1) {
            pageSize = Integer.MAX_VALUE;
        }
        if (null != keyword) {
            keyword = "%" + keyword + "%";
        }
        PageHelper.startPage(pageNum, pageSize);
        return userDAO.getStudentList(keyword, id);
    }


    //根据id得到学生信息
    public UserStudent getUserStudentByUserId(Integer id) {
        return userDAO.getUserStudentByUserId(id);
    }
    //根据studentId得到学生信息
    public UserStudent getStudentByStudentId(Integer id) {
        return userDAO.getStudentByStudentId(id);
    }

    public int addGood(GoodParam goodParam) {
        GoodInfo goodInfo = new GoodInfo(
                goodParam.getGoodId(),
                goodParam.getStudentId(),
                goodParam.getGoodName(),
                goodParam.getGoodType(),
                goodParam.getPrice(),
                goodParam.getDescription(),
              //  goodParam.getPhoto(),
                false //goodParam.getIsSold()
        );
        return userDAO.addGood(goodInfo);
    }

    public int modifyGood(GoodParam goodParam) {
        return userDAO.modifyGood(goodParam);
    }

    public List<GoodInfo> getGoodListByUserStudent(UserStudent userStudent) {
        return userDAO.getGoodListByStudentId(userStudent.getStudentId());
    }

    public List<GoodInfo> searchGoods(int pageNum, int pageSize, String keyword, int id) {
        if (pageSize == -1) {
            pageSize = Integer.MAX_VALUE;
        }
        if (null != keyword) {
            keyword = "%" + keyword + "%";
        }
        PageHelper.startPage(pageNum, pageSize);
        return userDAO.getGoodList(keyword, id);
    }

    public int deleteGood(int id) {
        return userDAO.deleteGood(id);
    }

    public int setGoodSold(int id) {
        return userDAO.setGoodSold(id);
    }

    public GoodDetailResult getGoodDetail(int goodId) {
        return userDAO.getGoodDetail(goodId);
    }

    public int addRequest(RequestsParam requestsParam) {
        RequestInfo requestInfo = new RequestInfo(
                requestsParam.getRequestId(),
                requestsParam.getStudentId(),
                requestsParam.getRequestName(),
                requestsParam.getRequestType(),
                requestsParam.getPrice(),
                requestsParam.getDescription(),
                false
        );
        return userDAO.addRequest(requestInfo);
    }


    public int modifyRequest(RequestsParam requestsParam){
        return userDAO.modifyRequest(requestsParam);
    }

    public List<RequestInfo> getRequestListByUserStudent(UserStudent userStudent){
        return userDAO.getRequestListById(userStudent.getStudentId());
    }

    public List<RequestInfo> getAllRequests(){
        return userDAO.getAllRequests();
    }

    public List<GoodInfo> getAllGoods(){
        return userDAO.getAllGoods();
    }

    public int deleteRequest(int id) {
        return userDAO.deleteRequest(id);
    }

    public int setRequestSupplied(int requestId) {
        return userDAO.setRequestSupplied(requestId);
    }


    public List<RequestInfo> searchRequests(int pageNum, int pageSize, String keyword, int id) {
        if (pageSize == -1) {
            pageSize = Integer.MAX_VALUE;
        }
        if (null != keyword) {
            keyword = "%" + keyword + "%";
        }
        PageHelper.startPage(pageNum, pageSize);
        return userDAO.getRequestList(keyword, id);
    }

    public RequestDetailResult getRequestDetail(int requestId) {
        return userDAO.getRequestDetail(requestId);
    }


}
